package rise.ui;

import rise.comunity.Status;
import rise.comunity.UserData;
import rise.message.Login;
import rise.net.ImmediateLoginTask;
import rise.net.OlivawPortsClient;
import rise.net.ReceiverService;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

public class Splash extends Activity {

	public static final String usernameKey = "USERNAME";
	public static final String passwordKey = "PASSWORD";
	public static final String statusKey = "STATUS";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_splash);

		SharedPreferences userInfo = this.getSharedPreferences("SHARED_PREFS",
				0);
		Runnable runnable = new SwitchToRegistration();
		runnable = quickStart(userInfo, runnable);

		MapActivity.handler = new MapRefreshHandler();
		UserListActivity.handler = new UserListRefreshHandler();
		Conversation.handler = new ConversationRefreshHandler();

		Handler handler = new Handler();
		int waitTime = 2000;
		if (runnable instanceof SwitchToUserListDirectly
				|| runnable instanceof SwitchToUserList) {
			waitTime = 0;
		}
		handler.postDelayed(runnable, waitTime);
	}

	private Runnable quickStart(SharedPreferences userInfo, Runnable runnable) {
		ReceiverService receiverService = ReceiverService
				.obtainReceiverService();
		if (UserData.obtainUserData() != null && receiverService != null) {
			runnable = new SwitchToUserListDirectly();

		} else if (UserData.obtainUserData() != null) {
			runnable = new SwitchToUserList();

		} else if (userInfo != null && userInfo.contains(usernameKey)
				&& userInfo.contains(passwordKey)
				&& userInfo.contains(statusKey)) {
			String username = userInfo.getString(usernameKey, null);
			String password = userInfo.getString(passwordKey, null);
			String status = userInfo.getString(statusKey, null);

			if (username != null && password != null && status != null) {
				UserData.createUserData(username, password,
						Status.valueOf(status));
				runnable = new SwitchToUserList();
			}
		}
		return runnable;
	}

	private class SwitchToUserListDirectly implements Runnable {
		@Override
		public void run() {
			Intent intent = new Intent(Splash.this, UserListActivity.class);
			Splash.this.startActivity(intent);
		}
	}

	private class SwitchToUserList implements Runnable {

		@Override
		public void run() {
			UserData userData = UserData.obtainUserData();
			Login login = new Login(userData.getUsername(),
					userData.getPassword(), OlivawPortsClient.getInputPort(),
					0, 0);

			new ImmediateLoginTask(Splash.this, login, Splash.this)
					.execute(new Void[0]);
		}
	}

	private class SwitchToRegistration implements Runnable {

		@Override
		public void run() {
			Intent intent = new Intent(Splash.this, AccessActivity.class);
			Splash.this.startActivity(intent);
		}
	}
}
